<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品列表</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <style>
        #pagination {
            display: flex;
            justify-content: center;
        }
    </style>
</head>
<body>

<div class="container mt-5">
    <h2>药品列表</h2>
    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addEditModal" id="addProductBtn">
        添加药品
    </button>
    <table id="productTable" class="table">
        <thead>
        <tr>
            <th scope="col">药品名称</th>
            <th scope="col">图片</th>
            <th scope="col">价格</th>
            <th scope="col">批准文号</th>
            <th scope="col">药品种类</th>
            <th scope="col">药品类别</th>
            <th scope="col">库存</th>
            <th scope="col">操作</th>
        </tr>
        </thead>
        <tbody id="productBody">
        <!-- Data will be dynamically added here -->
        </tbody>
    </table>

    <nav aria-label="Page navigation">
        <ul class="pagination" id="pagination"></ul>
    </nav>
</div>

<!-- Bootstrap JS and jQuery -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.min.js"></script>
<script src="/javascript/coco-message.js"></script>
<script>
  function previewImage() {
    var input = document.querySelector("#image")
    console.log(input.files)
    // 确保用户选择了文件
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      // 读取文件内容并在加载完成后显示图片
      reader.onload = function (e) {
        $("#previewImage").html('<img src="' + e.target.result + '" alt="Preview" style="width: 100px">')
      };

      // 读取文件内容为DataURL
      reader.readAsDataURL(input.files[0]);
    } else {
      $("#imagePreview").empty()
    }
  }

  $(document).ready(function () {
    var editProductId = null; // Store the product ID being edited

    var url = "http://127.0.0.1:12345"

    function loadData(page) {
      $.ajax({
        url: `${url}/medicine/?page=` + page, // Replace with your API endpoint
        method: 'GET',
        dataType: 'json',
        success: function (res) {
          if (res.code === 0) {
            updateTable(res.data);
            updatePagination(res.data);
          }
        },
        error: function (error) {
          console.log('Error fetching data:', error);
        }
      });
    }

    // 渲染数据
    function updateTable(data) {
      var tableBody = $('#productBody');
      tableBody.empty();

      $.each(data.list, function (index, product) {
        var row = '<tr>';
        row += '<td>' + product.name + '</td>';
        row += '<td>' + `<img src="${product.image}" style="width: 100px; height: 100px; object-fit: cover"/>` + '</td>';
        row += '<td>' + product.price + '</td>';
        row += '<td>' + product.approval_number + '</td>';
        row += '<td>' + product.type + '</td>';
        row += '<td>' + product.category + '</td>';
        row += '<td>' + product.repertory + '</td>';
        row += '<td>';
        row += '<button class="btn btn-sm btn-warning edit-btn" data-id="' + product.id + '">编辑</button> ';
        row += '<button class="btn btn-sm btn-danger delete-btn" data-id="' + product.id + '">删除</button>';
        row += '</td>';
        row += '</tr>';
        tableBody.append(row);
      });

      // 编辑药品
      $('.edit-btn').on('click', function () {
        editProductId = $(this).data('id');
        openAddEditModal('编辑药品', '提交');
        $.ajax({
          url: `${url}/medicine/${editProductId}/`,
          success: function (res) {
            $.each(res.data, function (key, value) {
              if (key !== "image") {
                $('#' + key).val(value);
              } else {
                $("#previewImage").html('<img src="' + `${url}${value}` + '" alt="Preview" style="width: 100px">')
              }
            });
          }
        })
      });

      // 删除药品
      $('.delete-btn').on('click', function () {
        var productId = $(this).data('id');
        if (confirm('确认删除?')) {
          deleteProduct(productId);
        }
      });
    }

    // Function to update pagination
    function updatePagination(pagination) {
      var paginationElement = $('#pagination');
      paginationElement.empty();
      let p =  Math.ceil(pagination.total / 10)
      for (var i = 1; i <= p; i++) {
        var liClass = i === pagination.currentPage ? 'page-item active' : 'page-item';
        var linkClass = 'page-link';

        var listItem = '<li class="' + liClass + '"><a class="' + linkClass + '" href="#" data-page="' + i + '">' + i + '</a></li>';
        paginationElement.append(listItem);
      }

      // Add click event to pagination links
      $('.page-link').on('click', function (e) {
        e.preventDefault();
        var page = $(this).data('page');
        loadData(page);
      });
    }

    // Function to delete a product
    function deleteProduct(productId) {
      $.ajax({
        url: `${url}/medicine/` + productId, // Replace with your delete API endpoint
        method: 'DELETE',
        success: function (response) {
          if (response.code === 0) {
            cocoMessage.success("删除成功")
            loadData(1);
          } else {
            cocoMessage.error("删除失败")
          }
        },
        error: function (error) {
          cocoMessage.error("网络错误")
          console.log('Error deleting product:', error);
        }
      });
    }

    // Function to open the add/edit modal
    function openAddEditModal(title, buttonLabel) {
      $('#modalTitle').text(title);
      console.log(buttonLabel)
      $('#modalSubmitBtn').text(buttonLabel);
      $('#addEditModal').modal('show');
    }

    // Add click event to "Add Product" button
    $('#addProductBtn').on('click', function () {
      editProductId = null;
      console.log("ddd")
      openAddEditModal('添加药品', '提交');
    });

    // Add submit event to the modal form
    $('#addEditForm').on('submit', function (e) {
      e.preventDefault();
      var formData = new FormData(this);
      var apiEndpoint = editProductId ? `${url}/medicine/` + editProductId : `${url}/medicine/`;
      $.ajax({
        url: apiEndpoint,
        method: editProductId ? 'PUT' : 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response) {
          console.log('Product saved successfully:', response);
          if (response.code === 0) {
            cocoMessage.success(editProductId ? "修改成功" : "添加成功")
          }
          $('#addEditModal').modal('hide');
          loadData(1);
        },
        error: function (error) {
          console.log('Error saving product:', error);
        }
      });
    });

    // Initial data load
    loadData(1);
    // 当模态框关闭时
    $('#addEditModal').on('hidden.bs.modal', function (event) {
      $('#addEditForm input, #addEditForm textarea').val('');
      $("#previewImage").empty()
    })
  });
</script>

<!-- Modal for Add/Edit Product -->
<div class="modal fade" id="addEditModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addEditForm">
                    <div style="max-height: 400px; overflow: auto">
                        <div class="mb-3">
                            <label for="name" class="form-label">药品名称</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="image" class="form-label">图片</label>
                            <input type="file" class="form-control" id="image" name="image" accept="image/*"
                                   onchange="previewImage()">
                            <div id="previewImage"></div>
                        </div>
                        <div class="mb-3">
                            <label for="approval_number" class="form-label">批准文号</label>
                            <input type="text" class="form-control" id="approval_number" name="approval_number"
                                   required>
                        </div>
                        <div class="mb-3">
                            <label for="repertory" class="form-label">库存</label>
                            <input type="text" class="form-control" id="repertory" name="repertory" required>
                        </div>
                        <div class="mb-3">
                            <label for="price" class="form-label">价格</label>
                            <input type="text" class="form-control" id="price" name="price" required
                                   onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                        </div>
                        <div class="mb-3">
                            <label for="type" class="form-label">药品种类</label>
                            <input type="text" class="form-control" id="type" name="type" required>
                        </div>
                        <div class="mb-3">
                            <label for="category" class="form-label">药品类别</label>
                            <select class="form-control" id="category" name="category">
                                <option label="非处方药" value="otc"></option>
                                <option label="处方药" value="pd"></option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="specification" class="form-label">规格</label>
                            <input type="text" class="form-control" id="specification" name="specification" required>
                        </div>
                        <div class="mb-3">
                            <label for="manufacturer" class="form-label">厂家</label>
                            <input type="text" class="form-control" id="manufacturer" name="manufacturer" required>
                        </div>
                        <div class="mb-3">
                            <label for="desc" class="form-label">描述</label>
                            <textarea type="text" class="form-control" id="desc" name="desc" required></textarea>
                        </div>
                    </div>
                    <div style="text-align: right">
                        <button type="submit" class="btn btn-primary" id="modalSubmitBtn"></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
